package com.yokead.controller.digging.template;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.base.DiggingBaseControl;
import com.yokead.service.template.TemplateService;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import com.yokead.util.EncryptUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jiangzeyin on 2018/5/12.
 */
@Controller
@RequestMapping("digging/template")
public class EditTemplateController extends DiggingBaseControl {
    @Resource
    private TemplateService templateService;


    @RequestMapping(value = "save2.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save2(String tag, String filePath) throws IOException {
        if (StringUtil.isEmpty(tag)) {
            return JsonMessage.getString(405, "tag错误");
        }
        if (StringUtil.isEmpty(filePath)) {
            return JsonMessage.getString(405, "操作错误：-1");
        }
        String path;
        try {
            path = EncryptUtil.decrypt(filePath);
            File file = new File(path);
            if (!file.exists()) {
                return JsonMessage.getString(500, "编辑失败,文件不存在，请联系管理员");
            }
        } catch (Exception e) {
            SystemLog.ERROR().error("保存错误", e);
            return JsonMessage.getString(500, "保存异常");
        }
        Object object = saveReq(tag);
        if (object instanceof String) {
            return object.toString();
        }
        Document document = (Document) object;
        File file = new File(path);
        backIndexHtml(file);
        FileUtil.writeString(document.outerHtml(), file, CharsetUtil.CHARSET_UTF_8);
        return JsonMessage.getString(200, "保存成功");
    }

    private Object saveReq(String tag) throws IOException {
        String title_ = getParameter("title");
        if (StringUtil.isEmpty(title_)) {
            return JsonMessage.getString(405, "请输入网页标题");
        }
        JSONArray jsonArray = templateService.getTemplateField(tag);
        if (jsonArray == null || jsonArray.size() <= 0) {
            return JsonMessage.getString(405, "tag不正确");
        }
        Document document = templateService.getTemplateDocument(tag);
        if (document == null) {
            return JsonMessage.getString(500, "模板异常");
        }
        Elements title = document.getElementsByTag("title");
        for (Element element : title) {
            element.text(title_);
            element.attr("pageTemplate", tag);
        }
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            String type = jsonObject.getString("type");
            int index = jsonObject.getIntValue("index");
            String text = jsonObject.getString("text");
            String name = String.format("%s_%s", type, index);
            if ("imgs".equals(type)) {
                String[] val = getParameters(name);
                if (val == null || val.length <= 0) {
                    return JsonMessage.getString(405, "请上传" + text);
                }
                Elements elements = new Elements();
                for (String item : val) {
                    Element img = new Element(Tag.valueOf("img"), "");
                    if (StringUtil.isEmpty(item)) {
                        continue;
                    }
                    img.attr("src", item);
                    elements.add(img);
                }
                if (elements.isEmpty()) {
                    return JsonMessage.getString(405, "请上传" + text);
                }
                Elements elements_type = document.select("[fieldtype='" + type + "']");
                for (Element element : elements_type) {
                    int fieldindex = StringUtil.parseInt(element.attr("fieldindex"));
                    if (fieldindex == index) {
                        element.html(elements.outerHtml());
                    }
                }
                continue;
            }
            String val = getParameter(name);
            if ("order".equals(type)) {
                Elements elements = document.select("[fieldtype='" + type + "']");
                for (Element element : elements) {
                    int fieldindex = StringUtil.parseInt(element.attr("fieldindex"));
                    if (fieldindex == index) {
                        element.attr("src", val);
                        int height = getParameterInt(name + "_height", 500);
                        element.attr("height", height + "px");
                    }
                }
            } else if ("tel".equals(type) || "sms".equals(type)) {
                Elements elements = document.select("[fieldtype='" + type + "']");
                for (Element element : elements) {
                    int fieldindex = StringUtil.parseInt(element.attr("fieldindex"));
                    if (fieldindex == index) {
                        element.attr("href", type + ":" + val);
                    }
                }
            } else if ("text".equals(type) || "textarea".equals(type)) {
                Elements elements = document.select("[fieldtype='" + type + "']");
                for (Element element : elements) {
                    int fieldindex = StringUtil.parseInt(element.attr("fieldindex"));
                    if (fieldindex == index) {
                        element.text(val);
                    }
                }
            } else if ("img".equals(type)) {
                if (StringUtil.isEmpty(val)) {
                    return JsonMessage.getString(405, "请上传" + text);
                }
                Elements elements = document.select("[fieldtype='" + type + "']");
                for (Element element : elements) {
                    int fieldindex = StringUtil.parseInt(element.attr("fieldindex"));
                    if (fieldindex == index) {
                        element.attr("src", val);
                    }
                }
            } else if ("html".equals(type)) {
                Elements elements = document.select("[fieldtype='" + type + "']");
                for (Element element : elements) {
                    int fieldindex = StringUtil.parseInt(element.attr("fieldindex"));
                    if (fieldindex == index) {
                        element.html(val);
                    }
                }
            } else if ("wxs".equals(type)) {
                String[] vals = StrUtil.splitToArray(val, ',');
                if (vals.length <= 0) {
                    return JsonMessage.getString(405, "请填写" + text);
                }
                Elements elements = document.select("[fieldtype='" + type + "']");
                for (Element element : elements) {
                    int fieldindex = StringUtil.parseInt(element.attr("fieldindex"));
                    if (fieldindex != index) {
                        break;
                    }
                    Element child = element.child(0);
                    Element select = child.getElementsByAttribute("id").first();
                    Elements eles = new Elements();
                    for (String str : vals) {
                        Element clone = child.clone();
                        select.html(str);
                        eles.add(clone);
                    }
                    element.html(eles.outerHtml());
                }
            }
        }
        return document;
    }

    @RequestMapping(value = "save.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save(String tag) throws IOException {
        if (StringUtil.isEmpty(tag)) {
            return JsonMessage.getString(405, "tag错误");
        }
        Object object = saveReq(tag);
        if (object instanceof String) {
            return object.toString();
        }
        Document document = (Document) object;
        String domain = getParameter("domain");
        String name = getParameter("name");
        boolean cover = "on".equalsIgnoreCase(getParameter("cover", ""));
        String path;
        try {
            path = EncryptUtil.decrypt(domain);
            File file = new File(path);
            if (!file.exists()) {
                return JsonMessage.getString(400, "不存在该信息");
            }
            if (StringUtil.isChinese(name)) {
                return JsonMessage.getString(400, "产品名称不能为中文");
            }
            File pr = new File(file, name);
            if (!cover && pr.exists()) {
                return JsonMessage.getString(400, "产品名已经存在");
            }
            backIndexHtml(pr);
            pr = new File(pr, "index.html");
            FileUtil.writeString(document.outerHtml(), pr.getPath(), CharsetUtil.CHARSET_UTF_8);
            return JsonMessage.getString(200, "保存成功");
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("保存失败", e);
            return JsonMessage.getString(500, "保存失败:" + e.getMessage());
        }
    }

    @RequestMapping(value = "edit_{tag}.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String edit(@PathVariable String tag) {
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                setAttribute("tip", "编辑失败,文件不存在，请联系管理员");
                return "digging/template/create";
            }
            Document document = Jsoup.parse(file, "UTF-8");
            Elements title = document.getElementsByTag("title");
            String titleStr = null;
            String pageTemplate = null;
            for (Element element : title) {
                pageTemplate = element.attr("pageTemplate");
                if (!StringUtil.isEmpty(pageTemplate)) {
                    titleStr = element.text();
                    break;
                }
            }
            //templateService.getTemplateField(pageTemplate);
            JSONArray jsonArray = templateService.getTemplateField(pageTemplate);
            JSONArray data = parseDom(document, jsonArray);
            if (data == null) {
                setAttribute("tip", "解析页面异常");
                return "digging/template/create";
            }
            setAttribute("title", titleStr);
            setAttribute("data", data);
            setAttribute("editTag", pageTemplate);
            setAttribute("array", jsonArray);
            setAttribute("filePath", tag);
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("编辑失败", e);
            setAttribute("tip", "编辑失败,参数错误，请联系管理员:" + e.getLocalizedMessage());
            return "digging/template/create";
        }
        return "digging/template/create";
    }

    private JSONArray parseDom(Document document, JSONArray jsonArray) {
        if (jsonArray == null) {
            return null;
        }
        Elements elements = document.select("[fieldtype]");
        if (elements.isEmpty()) {
            return null;
        }
        Map<String, Element> map = new HashMap<>();
        for (Element element : elements) {
            String fieldtext = element.attr("fieldtext");
            String fieldtype = element.attr("fieldtype");
            if (StringUtil.isEmpty(fieldtype)) {
                continue;
            }
            if (StringUtil.isEmpty(fieldtext)) {
                continue;
            }
            String fieldindex = element.attr("fieldindex");
            int index = StringUtil.parseInt(fieldindex, -1);
            if (index <= -1) {
                continue;
            }
            String name = String.format("%s_%s", fieldtype, fieldindex);
            map.put(name, element);
        }
        if (map.size() <= 0) {
            return null;
        }
        JSONArray val = new JSONArray();
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            String type = jsonObject.getString("type");
            int index = jsonObject.getIntValue("index");
            String name = String.format("%s_%s", type, index);
            Element element = map.get(name);
            if (element == null) {
                continue;
            }
            JSONObject data = new JSONObject();
            data.put("name", name);
            data.put("type", type);
            if ("sms".equals(type) || "tel".equals(type)) {
                String href = element.attr("href");
                if (StringUtil.isEmpty(href)) {
                    continue;
                }
                String[] strings = href.split(":");
                if (strings.length >= 2) {
                    data.put("val", strings[1]);
                }
            } else if ("text".equals(type) || "textarea".equals(type)) {
                data.put("val", element.text());
            } else if ("html".equals(type)) {
                data.put("val", StringUtil.filterHTML(element.html().replace("\n", "&#10;")));
            } else if ("order".equals(type)) {
                String src = element.attr("src");
                if (StringUtil.isEmpty(src)) {
                    continue;
                }
                String height = StringUtil.convertNULL(element.attr("height")).replace("px", "");
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("src", HtmlUtil.unescape(src));
                jsonObject1.put("height", height);
                data.put("val", jsonObject1);
            } else if ("img".equals(type)) {
                String src = element.attr("src");
                if (StringUtil.isEmpty(src)) {
                    continue;
                }
                data.put("val", src);
            } else if ("imgs".equals(type)) {
                Elements elements1 = element.getElementsByTag("img");
                JSONArray jsonArray1 = new JSONArray();
                for (Element element1 : elements1) {
                    String src = element1.attr("src");
                    if (StringUtil.isEmpty(src)) {
                        continue;
                    }
                    jsonArray1.add(src);
                }
                if (jsonArray1.size() > 0) {
                    data.put("val", jsonArray1);
                } else {
                    continue;
                }
            } else if ("wxs".equals(type)) {
                Elements children = element.children();
                String wx = "";
                for (Element ele : children) {
                    Element id = ele.getElementsByAttribute("id").first();
                    if (id == null) {
                        continue;
                    }
                    String text = id.text();
                    if (StrUtil.isEmpty(wx)) {
                        wx = text;
                    } else {
                        wx += "," + text;
                    }
                }
                data.put("val", wx);
            }
            if (data.isEmpty()) {
                continue;
            }
            val.add(data);
        }
        return val;
    }
}
